package com.sakura.demo.gateway.filter;


import com.sakura.demo.common.constant.AuthConstant;
import com.sakura.demo.gateway.config.IgnoreUrlsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/**
 * @Author: zhengcan
 * @Date: 2022/5/13
 * @Description: 白名单路径访问时需要移除JWT请求头
 * @Version: 1.0.0 创建
 */
@Component
public class IgnoreUrlsRemoveJwtFilter implements WebFilter {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain filterChain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri = request.getURI();
        AntPathMatcher matcher = new AntPathMatcher();
        // 白名单路径移除JWT请求头
        List<String> urls = ignoreUrlsConfig.getUrls();
        if (!CollectionUtils.isEmpty(urls)) {
            urls.forEach(url -> {
                if (matcher.match(url, uri.getPath())) {
                    ServerHttpRequest newRequest = exchange.getRequest().mutate().header(AuthConstant.TOKEN_HEADER, "").build();
                    exchange.mutate().request(newRequest).build();
                }
            });
        }
        return filterChain.filter(exchange);
    }

}
